import settings from "../utils/settings";
import { location } from "../utils/getLocation";
import { guiMover } from "../utils/gui";
import { drawBoxAtEntity, timedisplay , RemoveEmoji, DrawString, sendEssentialNotifications, getItemSBID, drawQuadsAtPos, drawQuadsAtEntity, getEntityHP, newItemStackFrom, ServerTick } from "../utils/utils";
import BeaconBeam from "../../BeaconBeam";
import { Vec3 } from "../utils/vec3";

export function slayer() {}

//没接slayer提示
let weaponxp = 0;
let slayerquestcheck = false;

register("chat",() => {
    if(settings.noslayerquest && location.inSkyblock){
        slayerquestcheck = true;

        let mobdeadcheck = register("entityDeath", () => {
            if(slayerquestcheck && Player?.getHeldItem()){
                let itemstats = Player?.getHeldItem()?.getNBT()?.getCompoundTag("tag")?.getCompoundTag("ExtraAttributes").toObject();
                if(itemstats.champion_combat_xp){
                    if(itemstats.champion_combat_xp > weaponxp){
                        Client.showTitle("","§c您是不是没接slayer任务",0,35,5);
                    }
                    weaponxp = itemstats.champion_combat_xp;
                }
            }
        })

        let slayerqueststart = register("chat",() => {
            if(slayerquestcheck) slayerquestcheck = false;
        }).setChatCriteria("  SLAYER QUEST STARTED!")

        let worldload = register("worldLoad", () => {
            if(slayerquestcheck) slayerquestcheck = false;
        })

        setTimeout(() => {
            mobdeadcheck.unregister();
            slayerqueststart.unregister();
            worldload.unregister();
        }, 5*60*1000);
    }
}).setChatCriteria("  SLAYER QUEST FAILED!");

//pigman sword
let pigmansword = null;

//创建一个检测猪人声音的触发器
let pigmanswordsound = register("soundPlay",(position,name,vol,pitch,category,event) => {
    if(name == "mob.zombiepig.zpigangry") {
        pigmansword = ServerTick.getTime();
        //运行完后删除触发器
        pigmanswordsound.unregister();
    };
})//然后先关了
pigmanswordsound.unregister();

//创建一个检测玩家互动的触发器
register("playerInteract", (action, position, event) =>{
    //如果在设置里关了,那就关了
    if(!settings.pigmansword) return;
    //如果猪人剑还在冷却,就不继续执行了
    if(pigmansword) return;
    //看看手上是不是猪人剑
    if(Player.getHeldItem()?.getName()?.removeFormatting()?.includes("Pigman Sword")){
        //打开检测声音的触发器
        pigmanswordsound.register();
        //都半秒过去了还没叫声那肯定没放出来
        setTimeout(() => {
            pigmanswordsound.unregister();
        }, 500);
    }
})

//冷却时在hud显示
register("renderOverlay",() => {
    if(!settings.pigmansword) return;
    if(guiMover.gui.isOpen()) {
        DrawString((location.island == "The Rift" ? "§bHoly Ice: §a1.250s" : "§6Pigman: 3.141s"), guiMover.settings.PigmanSword.x , guiMover.settings.PigmanSword.y , guiMover.settings.PigmanSword.s , true);
        return;
    }
    if(!pigmansword || location.island == "The Rift") return;
    if(ServerTick.getTime() - pigmansword > 5000) {pigmansword = null; return;}
    DrawString("§6Pigman: " + timedisplay(5000 - (ServerTick.getTime() - pigmansword)) , guiMover.settings.PigmanSword.x , guiMover.settings.PigmanSword.y , guiMover.settings.PigmanSword.s , true);
})

//Ragnarock Axe
let Ragnarock = {
    time: 0,
    duration: 0,
    cooldown: 0,
    text: "",
    canceld: false,
    Finished: false,
    use() {
        if(settings.RagnarockAxe == 0 || !location.inSkyblock) return;
        if(!this.canceld && this.time == 0 && this.duration == 0) {
            this.time = ServerTick.getTime() + 2800;
            this.cooldown = ServerTick.getTime() + 19800;
            this.Finished = false;
        }
    },
    cancelled() {
        if(!this.canceld && this.time == 0 && this.duration == 0 && this.cooldown == 0) this.cooldown = ServerTick.getTime() + 19800;
        this.time = 0;
        this.duration = 0;
        this.text = "";
        this.canceld = true;
        this.Finished = false;
        setTimeout(() => {
            this.canceld = false;
        }, 3000);
    },
    UpdateText() {
        if(settings.RagnarockAxe == 0 || !location.inSkyblock) return;
        if (this.time == 0 && this.duration == 0 && this.cooldown == 0) {
            this.text = "";
            return;
        }
        if (this.time) {
            if (this.time - ServerTick.getTime() > 0) {
                switch (settings.RagnarockAxe) {
                    case 1:
                        this.text = "§5Ragnarock: §b" + timedisplay(this.time - ServerTick.getTime());
                        break;
                    case 2:
                        let num = Math.min(20, parseInt((3000 - (this.time - ServerTick.getTime()))/(3000/20)) + 1);
                        this.text = "§5Ragnarock: §b[§a" + '|'.repeat(num) + "§e" + '|'.repeat(20 - num) + "§b]";
                        break;
                }
            } else {
                this.duration = ServerTick.getTime() + 10000;
                this.time = 0;
            }
        } else if (this.duration) {
            if (this.duration - ServerTick.getTime() > 0) {
                switch (settings.RagnarockAxe) {
                    case 1:
                        this.text = "§5Ragnarock: §a" + timedisplay(this.duration - ServerTick.getTime());
                        break;
                    case 2:
                        let num = Math.min(20, parseInt((this.duration - ServerTick.getTime())/(10000/20)) + 1);
                        this.text = "§5Ragnarock: §b[§a" + '|'.repeat(num) + "§c" + '|'.repeat(20 - num) + "§b]";
                        break;
                }
            } else {
                this.duration = 0;
                this.Finished = true;
            }
        } else {
            if (this.cooldown - ServerTick.getTime() > 0) {
                switch (settings.RagnarockAxe) {
                    case 1:
                        this.text = "§5Ragnarock: §c" + timedisplay(this.cooldown - ServerTick.getTime());
                        break;
                    case 2:
                        let num = Math.min(20, parseInt(((this.Finished ? 7000 : 20000) - (this.cooldown - ServerTick.getTime()))/((this.Finished ? 7000 : 20000)/20)));
                        this.text = "§5Ragnarock: §b[§e" + '|'.repeat(num) + "§c" + '|'.repeat(20 - num) + "§b]";
                        break;
                }
            } else {
                this.cooldown = 0;
            }
        }
    }
}
register("actionBar", () => {
    Ragnarock.use();
}).setCriteria("CASTING IN 3s").setParameter("contains");

register("chat", () => {
    Ragnarock.cancelled();
}).setCriteria("Ragnarock was cancelled due to taking damage!");
register("actionBar", () => {
    Ragnarock.cancelled();
}).setCriteria("CANCELLED").setParameter("contains");

register("worldLoad", () => {
    Ragnarock.time = 0;
    Ragnarock.duration = 0;
    Ragnarock.cooldown = 0;
})

//在hud显示
register("renderOverlay",() => {
    if(settings.RagnarockAxe == 0) return;
    if(guiMover.gui.isOpen()) {
        DrawString((settings.RagnarockAxe == 2 ? "§5Ragnarock: §b[§a|||||§e|||||||||||||||§b]" : "§5Ragnarock: §b2.250s") , guiMover.settings.RagnarockAxe.x , guiMover.settings.RagnarockAxe.y , guiMover.settings.RagnarockAxe.s , true)
        return;
    }
    Ragnarock.UpdateText();
    if(Ragnarock.text == "") return;
    DrawString(Ragnarock.text , guiMover.settings.RagnarockAxe.x , guiMover.settings.RagnarockAxe.y , guiMover.settings.RagnarockAxe.s , true)
})


//reaper
let reaperSoundTimer = 0;
let reaperTimer = 0;
let reaperCooldown = 0;
register("soundPlay", (pos,name,vol,pit,cate,event) => {
    if(!settings.ReaperArmor || !location.inSkyblock) return;
    if(name != "mob.zombie.remedy" || pit != 1) return;
    reaperSoundTimer = ServerTick.getTime();
})
register("step",() => {
    if(!settings.ReaperArmor || !location.inSkyblock) return;
    if(reaperSoundTimer == 0 || ServerTick.getTime() - reaperSoundTimer > 6000) return;
    let boots = new Item(Player.getPlayer().func_71124_b(1));
    if(boots == null || getItemSBID(boots) != "REAPER_BOOTS") return;
    if(boots.getNBT().getCompoundTag("tag").getCompoundTag("display").getInteger("color") != 16711680) return;
    reaperTimer = reaperSoundTimer + 6000;
    reaperCooldown = reaperSoundTimer + 25000;
    reaperSoundTimer = 0;
})

register("renderOverlay",() => {
    if(!settings.ReaperArmor) return;
    if(guiMover.gui.isOpen()) {
        DrawString("§2Reaper: §a1.919s" , guiMover.settings.ReaperArmor.x , guiMover.settings.ReaperArmor.y , guiMover.settings.ReaperArmor.s , true)
        return;
    }
    if(!location.inSkyblock || reaperCooldown == 0) return;
    let text = "§2Reaper: ";
    if(reaperTimer > ServerTick.getTime()) {
        text += "§a" + timedisplay(reaperTimer - ServerTick.getTime());
    } else if(reaperCooldown > ServerTick.getTime()) {
        text += "§e" + timedisplay(reaperCooldown - ServerTick.getTime());
    } else {
        reaperTimer = 0;
        reaperCooldown = 0;
        return;
    }
    DrawString(text , guiMover.settings.ReaperArmor.x , guiMover.settings.ReaperArmor.y , guiMover.settings.ReaperArmor.s , true)
})

register("worldLoad", () => {
    reaperSoundTimer = 0;
    reaperTimer = 0;
    reaperCooldown = 0;
})


//slayer boss的一些基本属性
let slayerentity = {
    SlayerType: "",
    "Revenant Horror" : {type: net.minecraft.entity.monster.EntityZombie,
        DetectionRange: 0.7, widthX: 1, widthZ: 1, height: 2,
        Name: "Revenant Horror"},
    "Tarantula Broodfather" : {type: net.minecraft.entity.monster.EntitySpider,
        DetectionRange: 1.2, widthX: 1.8, widthZ: 1.8, height: 0.6,
        Name: "Tarantula Broodfather"},
    "Sven Packmaster" : {type: net.minecraft.entity.passive.EntityWolf,
        DetectionRange: 0.5, widthX: 1, widthZ: 1, height: 1,
        Name: "Sven Packmaster"},
    "Voidgloom Seraph" : {type: net.minecraft.entity.monster.EntityEnderman,
        DetectionRange: 0.5, widthX: 1, widthZ: 1, height: 3,
        Name: "Voidgloom Seraph"},
    "Inferno Demonlord" : {type: net.minecraft.entity.monster.EntityBlaze,
        DetectionRange: 0.5, widthX: 1, widthZ: 1, height: 2,
        Name: "Inferno Demonlord"},
    "Riftstalker Bloodfiend" : {type: net.minecraft.client.entity.EntityOtherPlayerMP,
        DetectionRange: 0.5, widthX: 1, widthZ: 1, height: 2,
        Name: "Bloodfiend"},
};

const healthRegExp = /((§[ae][0-9]+[a-zA-Z])§f\/§a[0-9]+[a-zA-Z]§c❤)/i;
function healthToString(entityHP) {
    let hp = Math.floor(entityHP.hp);
    if(entityHP.maxhp < 10000) return "§" + (entityHP.hp / entityHP.maxhp > 0.5 ? "a" : "e") + hp + "§c❤";
    for (let i = 0; i < 4; i++) {
        if (hp >= 1000) {
            hp = hp / 1000;
        } else {
            let hpString = "§" + (entityHP.hp / entityHP.maxhp > 0.5 ? "a" : "e") + parseFloat(hp.toFixed(2));
            switch (i) {
                case 0:
                    return hpString + "§c❤";
                case 1:
                    return hpString + "k§c❤";
                case 2:
                    return hpString + "M§c❤";
                case 3:
                    return hpString + "B§c❤";
            }
        }
    }
    return "§" + (entityHP.hp / entityHP.maxhp > 0.5 ? "a" : "e") + parseFloat(hp.toFixed(2)) + "T§c❤";
}

//烈焰人Slayer的一些东西
const NextBlazeAttuned = {ASHEN:"§f§lSPIRIT",SPIRIT:"§e§lAURIC",AURIC:"§b§lCRYSTAL",CRYSTAL:"§8§lASHEN"};
const BlazeDagger = {272:"§8§lASHEN",267:"§f§lSPIRIT",283:"§e§lAURIC",276:"§b§lCRYSTAL"};
const Inferno = {EntitySkeleton:"ⓆⓊⒶⓏⒾⒾ",EntityPigZombie:"ⓉⓎⓅⒽⓄⒺⓊⓈ"};
function isBlazeDagger(item) {
    if(!item) return false;
    const id = getItemSBID(item);
    if(!id) return false;
    if(["FIREDUST_DAGGER","MAWDUST_DAGGER","BURSTFIRE_DAGGER","BURSTMAW_DAGGER","HEARTFIRE_DAGGER","HEARTMAW_DAGGER"].indexOf(id) != -1) return true; else return false;
}


//检测slayer BOSS
let slayerBoss = {
    entity : undefined,
    hp : "",
    hpTag : "",
    timeLeft : "",
    renderStr : "",
    voidgloom : {lazer : 0, beacon : {status : "", entity : null, loc : null, time : 0}},
    inferno : [],
    infernoStatus : {
        status : "",
        counts : 0,
        hit : false,
        repeat : []
    },
    reset() {
        this.entity = undefined;
        this.hp = "";
        this.hpTag = "";
        this.timeLeft = "";
        this.renderStr = "";
        this.voidgloom = {lazer : 0, beacon : {status : "", entity : null, loc : null, time : 0}};
        this.inferno = [];
        this.infernoStatus = {status : "", counts : 0, hit : false, repeat : []};
    }
};

register("attackEntity", (entity,event) => {
    if(!location.inSkyblock || !settings.SlayerBossInfo || settings.BlazeSlayerInfo < 3 || slayerentity.SlayerType != "Inferno Demonlord") return;
    if(slayerBoss.entity == undefined || entity.getUUID() != slayerBoss.entity.getUUID()) return;
    if(slayerBoss.infernoStatus.status != "ASHEN" && slayerBoss.infernoStatus.status != "AURIC") return;
    const item = Player.getHeldItem();
    if(!isBlazeDagger(item)) return;
    if(BlazeDagger[item.getID()].removeFormatting() != slayerBoss.infernoStatus.status) return;
    slayerBoss.infernoStatus.hit = true;
})

register("tick", () => {
    if(!location.inSkyblock) {slayerBoss.reset();return;};

    //看看有没有接slayer并获取计分板中写着slayer信息的位置
    let SlayerQuest = null;  
    if(slayerBoss.entity && slayerBoss.entity.isDead()) slayerBoss.reset();
    Scoreboard.getLines().forEach((s,i) => {
        if(RemoveEmoji(s.toString().removeFormatting()) == "Slayer Quest") SlayerQuest = i;
    })
    if(!SlayerQuest) {slayerBoss.reset();return;};
    
    //看看接的是哪个slayer
    const bossName = RemoveEmoji(Scoreboard.getLineByIndex(SlayerQuest - 1).toString()).removeFormatting().split(' ').slice(0,2).join(' ');
    if(!bossName || slayerentity[bossName] == undefined) {slayerBoss.reset();return;};
    slayerentity.SlayerType = bossName;
    const BossParameter = slayerentity[bossName];

    //看看是否正在boss战,然后通过写着玩家ID的盔甲架来寻找slayer boss
    try {
        if(!Scoreboard.getLineByIndex(SlayerQuest - 2).toString().includes("Slay the boss")) {slayerBoss.reset();return;};
        if(bossName == "Inferno Demonlord" && slayerBoss.inferno.length != 0) slayerBoss.inferno = slayerBoss.inferno.filter(e => e && !e.isDead());
        const ArmorStand = World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(ArmorStand => ArmorStand && ArmorStand.getName().includes("Spawned") && ArmorStand.getName().includes(Player.getName()))[0];
        
        if(ArmorStand == undefined) {
            //烈焰人boss分裂时的猪人和骷髅
            if(bossName != "Inferno Demonlord" || slayerBoss.entity == undefined) return;
            const pigman = World.getAllEntitiesOfType(net.minecraft.entity.monster.EntityPigZombie).filter(e => e && e.distanceTo(slayerBoss.entity) < 3.5 && e.getY() > slayerBoss.entity.getY() - 0.5);
            const skeleton = World.getAllEntitiesOfType(net.minecraft.entity.monster.EntitySkeleton).filter(e => e && e.getEntity().func_82202_m() == 1 && e.distanceTo(slayerBoss.entity) < 3.5  && e.getY() > slayerBoss.entity.getY() - 0.5);
            if(skeleton.length == 1 && slayerBoss.inferno.length < 2 && slayerBoss.inferno.filter(e => e.getClassName() == "EntitySkeleton").length == 0) slayerBoss.inferno.push(skeleton[0]);
            if(pigman.length == 1 && slayerBoss.inferno.length < 2 && slayerBoss.inferno.filter(e => e.getClassName() == "EntityPigZombie").length == 0) slayerBoss.inferno.push(pigman[0]);
            if(!settings.BlazeSlayerInfo) return;
            let BossStatus = slayerBoss.timeLeft.split(' ');
            BossStatus.pop();
            BossStatus.push("§7→§r");
            BossStatus.push(NextBlazeAttuned[BossStatus[0].removeFormatting()]);
            let currentlyShield = "";
            let InfernoMobsStr = [];
            slayerBoss.inferno.forEach(e => {
                const armorStand = World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(a => a && a.distanceTo(e) < 3);
                const hp = armorStand.filter(a => a.getName().includes("❤") && a.getName().includes(Inferno[e.getClassName()]));
                if(hp.length == 1) InfernoMobsStr.push('\n' + hp[0].getName().split(' ').slice(1).join((e.getClassName() == "EntitySkeleton" ? "     " : " ")));
                const timeleft = armorStand.filter(a => a.getName().search(/[0-9]{1,2}:[0-9]{1,2}/) != -1);
                if(timeleft.length == 1) {
                    let str = timeleft[0].getName().split(' ');
                    str.pop();
                    InfernoMobsStr.push(str.join(' '));
                    if(str[0].removeFormatting() != "IMMUNE") currentlyShield = str[0].removeFormatting();
                }
            })
            if(Client.settings.getSettings().field_74320_O === 1) {
                const item = Player.getHeldItem();
                if(isBlazeDagger(item)) BossStatus.push((BlazeDagger[item.getID()].removeFormatting() == currentlyShield ? "\n§a" : "\n§e") + "当前手持匕首§7:§r " + BlazeDagger[item.getID()]);
                else BossStatus.push("\n§e当前手持§7:§r " + item.getName());
            }
            slayerBoss.renderStr = '§eInferno Demonlord ' + slayerBoss.hp.split(' ').pop() + '\n' + BossStatus.join(' ') + InfernoMobsStr.join(' ');
            return;
        }

        const bossEntity = World.getAllEntitiesOfType(BossParameter.type).filter(e => new Vec3(e.getX(),e.getY() + BossParameter.height,e.getZ()).distance(new Vec3(ArmorStand)) < BossParameter.DetectionRange && e.getY() < ArmorStand.getY() && (bossName != "Tarantula Broodfather" || e.getClassName() == "EntitySpider") && (bossName != "Riftstalker Bloodfiend" || e.getName() === "Bloodfiend "));
        if(bossEntity.length == 1.0) slayerBoss.entity = bossEntity[0];
        let NearbyArmorStand = World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(e => e.getName() != ArmorStand.getName() && e.distanceTo(ArmorStand) < 1 && Math.abs(e.getRenderX() - ArmorStand.getRenderX()) < 0.5 && Math.abs(e.getRenderZ() - ArmorStand.getRenderZ()) < 0.5);
        slayerBoss.hpTag = NearbyArmorStand.filter(e => e.getName().removeFormatting().includes((bossName == "Revenant Horror" && slayerBoss.entity != undefined && getEntityHP(slayerBoss.entity).maxhp > 6000000) ? "Atoned Horror" : BossParameter.Name))[0]?.getName();
        slayerBoss.hp = (slayerBoss.hpTag?.includes("ᛤ") ? "§5ᛤ§r " : "") + (slayerBoss.entity ? healthToString(getEntityHP(slayerBoss.entity)) : slayerBoss.hpTag?.match(healthRegExp)[2] + "§c❤");
        if(NearbyArmorStand.filter(e => e.getName().includes(':'))[0])
            slayerBoss.timeLeft = NearbyArmorStand.filter(e => e.getName().includes(':'))[0].getName();

        //末影人猎手的激光和信标
        if(bossName == "Voidgloom Seraph" && settings.EndermanSlayerInfo >= 2) {
            if(slayerBoss.entity.getRiding() && World.getAllEntitiesOfType(net.minecraft.entity.monster.EntityGuardian).filter(e => e.distanceTo(slayerBoss.entity) < 3).length >= 1) {
                if(slayerBoss.voidgloom.lazer < ServerTick.getTime()) slayerBoss.voidgloom.lazer = ServerTick.getTime() + 7200;
            } else slayerBoss.voidgloom.lazer = 0;

            switch (true) {
                case (slayerBoss.entity.getEntity().func_175489_ck() == "minecraft:beacon"):
                    slayerBoss.voidgloom.beacon.status = "holding";
                    break;
                case (slayerBoss.voidgloom.beacon.status == "holding" && slayerBoss.entity.getEntity().func_175489_ck() == "minecraft:air"):
                    let beacon = World.getAllEntitiesOfType(net.minecraft.entity.item.EntityArmorStand).filter(e => e.getEntity().func_71124_b(4) && e.getEntity().func_71124_b(4).func_77977_a() == "tile.beacon" && e.distanceTo(slayerBoss.entity) < 3);
                    if(beacon.length == 1) {
                        slayerBoss.voidgloom.beacon.entity = beacon[0];
                        slayerBoss.voidgloom.beacon.status = "§ethrown";
                    }
                    break;
                case (slayerBoss.voidgloom.beacon.status == "§ethrown" && slayerBoss.voidgloom.beacon.entity && slayerBoss.voidgloom.beacon.entity.isDead()):
                    let TileBeacon = World.getAllTileEntitiesOfType(net.minecraft.tileentity.TileEntityBeacon).filter(e => e.getBlockPos().distance(slayerBoss.voidgloom.beacon.entity.getPos()) < 3.5);
                    if(TileBeacon.length >= 1) {
                        slayerBoss.voidgloom.beacon.status = "onTheGround";
                        slayerBoss.voidgloom.beacon.loc = TileBeacon[0].getBlockPos();
                        slayerBoss.voidgloom.beacon.entity = null;
                        slayerBoss.voidgloom.beacon.time = ServerTick.getTime() + 4800;
                    } else if(slayerBoss.voidgloom.beacon.status == "§ethrown") slayerBoss.voidgloom.beacon = {status : "", entity : null, loc : null, time : 0};
                    break;
                case (slayerBoss.voidgloom.beacon.status == "onTheGround" && (slayerBoss.voidgloom.beacon.time < ServerTick.getTime() || World.getBlockAt(slayerBoss.voidgloom.beacon.loc).getType().getRegistryName() === "minecraft:air")):
                    slayerBoss.voidgloom.beacon = {status : "", entity : null, loc : null, time : 0};
                    break;
            }
        }
        
        //整理一下要显示在屏幕上的东西
        let BossStatus = [];
        switch (bossName) {
            case "Revenant Horror":
                if(settings.ZombieSlayerInfo == 0) return;
                if(slayerBoss.timeLeft.split(' ').length > 1) {
                    BossStatus = slayerBoss.timeLeft.split(' ');
                    BossStatus.pop();
                }
                slayerBoss.renderStr = '§bRevenant Horror ' + slayerBoss.hp + (settings.ZombieSlayerInfo >= 2 ? '\n' + ( slayerBoss.timeLeft.split(' ').length > 1 ? BossStatus.join(' ') : "") : "");
                break;
            case "Tarantula Broodfather":
                if(settings.SpiderSlayerInfo == 0) return;
                slayerBoss.renderStr = '§4Tarantula Broodfather ' + slayerBoss.hp;
                break;
            case "Sven Packmaster":
                if(settings.WolfSlayerInfo == 0) return;
                if(slayerBoss.timeLeft.split(' ').length > 1) {
                    BossStatus = slayerBoss.timeLeft.split(' ');
                    BossStatus.pop();
                }
                slayerBoss.renderStr = '§fSven Packmaster ' + slayerBoss.hp + (settings.WolfSlayerInfo >= 2 ? '\n' + ( slayerBoss.timeLeft.split(' ').length > 1 ? BossStatus.join(' ') : "") : "");
                break;
            case "Voidgloom Seraph":
                if(settings.EndermanSlayerInfo == 0) return;
                slayerBoss.renderStr = '§5Voidgloom Seraph ' + slayerBoss.hp + 
                 (slayerBoss.hpTag && slayerBoss.hpTag.includes("Hit") ? "\n§fHit Phase: " + slayerBoss.hpTag.removeFormatting().replace(/[^0-9]/g,"") + " Hits" : "") + (settings.EndermanSlayerInfo < 2 ? "" :
                 (slayerBoss.voidgloom.lazer ? "\n§aLazer: §e" + timedisplay(slayerBoss.voidgloom.lazer - ServerTick.getTime()) : "") + 
                 (slayerBoss.voidgloom.beacon.status != "" ? "\n§bBeacon: " + (slayerBoss.voidgloom.beacon.status == "onTheGround" ? "§c" + timedisplay(slayerBoss.voidgloom.beacon.time - ServerTick.getTime()) : slayerBoss.voidgloom.beacon.status) : ""));
                break;
            case "Inferno Demonlord":
                if(settings.BlazeSlayerInfo == 0) return;
                if(slayerBoss.timeLeft.split(' ').length > 1) {
                    BossStatus = slayerBoss.timeLeft.split(' ');
                    BossStatus.pop();
                    BossStatus.push("§7→§r");
                    BossStatus.push(NextBlazeAttuned[BossStatus[0].removeFormatting()]);
                    if(Client.settings.getSettings().field_74320_O === 1) {
                        const item = Player.getHeldItem();
                        if(isBlazeDagger(item)) BossStatus.push((BlazeDagger[item.getID()].removeFormatting() === BossStatus[0].removeFormatting() ? "\n§a" : "\n§e") + "当前手持匕首§7:§r " + BlazeDagger[item.getID()]);
                        else BossStatus.push("\n§e当前手持§7:§r " + item.getName());
                    }
                    if(settings.BlazeSlayerInfo >= 3) {
                        if(slayerBoss.infernoStatus.hit) {
                            if(slayerBoss.infernoStatus.status != BossStatus[0].removeFormatting() || slayerBoss.infernoStatus.counts > parseInt(RemoveEmoji(BossStatus[1].removeFormatting()))) {
                                slayerBoss.infernoStatus.repeat.push(Date.now());
                                slayerBoss.infernoStatus.hit = false;
                            }
                        }
                        slayerBoss.infernoStatus.status = BossStatus[0].removeFormatting();
                        slayerBoss.infernoStatus.counts = parseInt(RemoveEmoji(BossStatus[1].removeFormatting()));
                        slayerBoss.infernoStatus.repeat = slayerBoss.infernoStatus.repeat.filter(e => Date.now() - e < 6000);
                        slayerBoss.infernoStatus.repeat.forEach(e => {
                            BossStatus.push("\n§6Repeat§7: §e" + timedisplay(6000 - (Date.now() - e)));
                        })
                    }
                }
                slayerBoss.renderStr = '§bInferno Demonlord ' + slayerBoss.hp.split(' ').pop() +(settings.BlazeSlayerInfo >= 2 ? '\n' + ( slayerBoss.timeLeft.split(' ').length > 1 ? BossStatus.join(' ') : "") : "");
                break;
            case "Riftstalker Bloodfiend":
                if(settings.VampireSlayerInfo == 0) return;
                let VampireStatus = "";
                if(slayerBoss.timeLeft.split(' ').length > 1) {
                    BossStatus = slayerBoss.timeLeft.split(' ').slice(1);
                    for (let i = 0; i < BossStatus.length; i++) {
                        VampireStatus += BossStatus[i] + (BossStatus[i].removeFormatting() == "KILLER" ? " " + BossStatus[++i] : "") + ' ' + BossStatus[++i] + '\n';
                    }
                }
                slayerBoss.renderStr = "§4Bloodfiend " + (slayerBoss.hp.includes("҉") ? slayerBoss.hp.split(' ').slice(-2).join(' ') : slayerBoss.hp.split(' ').pop()) + (settings.VampireSlayerInfo >= 2 ? '\n' + VampireStatus : "");
                break;
        };
    } catch (error) {}
})

//显示boss血量在屏幕上
register("renderOverlay",() => {
    if(!settings.SlayerBossInfo) return;
    if(guiMover.gui.isOpen()) {
        DrawString((location.island == "The Rift" ? "§4Bloodfiend §b1234§c❤" : "§5Voidgloom Seraph §a205M§c❤") , guiMover.settings.SlayerBoss.x , guiMover.settings.SlayerBoss.y , guiMover.settings.SlayerBoss.s , true);
        return;
    }
    if(!location.inSkyblock || slayerBoss.renderStr == "") return;
    DrawString(slayerBoss.renderStr , guiMover.settings.SlayerBoss.x , guiMover.settings.SlayerBoss.y , guiMover.settings.SlayerBoss.s , true);
})

//在slayer boss旁边标个框
register("renderWorld", (ticks) => {
    if(!settings.boxslayerboss || !location.inSkyblock || slayerBoss.entity == undefined) return;
    const BossParameter = slayerentity[slayerentity.SlayerType];
    if(!BossParameter) return;
    drawBoxAtEntity(slayerBoss.entity,(settings.boxbosscolor.getRed()/255),(settings.boxbosscolor.getGreen()/255),(settings.boxbosscolor.getBlue()/255),(settings.boxbosscolor.getAlpha()/255),BossParameter.widthX,BossParameter.widthZ,BossParameter.height,ticks,5,settings.boxslayerboss >= 2);
    if(settings.boxslayerboss == 3) BeaconBeam(slayerBoss.entity.getX() + 0.5,slayerBoss.entity.getY(),slayerBoss.entity.getZ() + 0.5,(settings.boxbosscolor.getRed()/255),(settings.boxbosscolor.getGreen()/255),(settings.boxbosscolor.getBlue()/255),(settings.boxbosscolor.getAlpha()/255),true);
    if(slayerBoss.voidgloom.beacon.loc != null) BeaconBeam(slayerBoss.voidgloom.beacon.loc.x,slayerBoss.voidgloom.beacon.loc.y,slayerBoss.voidgloom.beacon.loc.z,1,1,1,0.5,true);
    if(slayerBoss.inferno.length != 0) slayerBoss.inferno.forEach(e => {
        drawBoxAtEntity(e,(settings.boxbosscolor.getRed()/255),(settings.boxbosscolor.getGreen()/255),(settings.boxbosscolor.getBlue()/255),(settings.boxbosscolor.getAlpha()/255),BossParameter.widthX,BossParameter.widthZ,BossParameter.height,ticks,5,settings.boxslayerboss >= 2);
        if(settings.boxslayerboss == 3) BeaconBeam(e.getX() + 0.5,e.getY(),e.getZ() + 0.5,(settings.boxbosscolor.getRed()/255),(settings.boxbosscolor.getGreen()/255),(settings.boxbosscolor.getBlue()/255),(settings.boxbosscolor.getAlpha()/255),true);
    });
})

//标记血量低于20%的吸血鬼boss
register("renderWorld", () => {
    if(!settings.BoxLowHPBloodfiend || !location.inSkyblock || location.island != "The Rift" || location.location != "Stillgore Château") return;
    World.getAllPlayers().filter(e => e && !e.isDead() && e.getName() === "Bloodfiend " && ((getEntityHP(e).hp / getEntityHP(e).maxhp) <= 0.2)).forEach(e => { drawQuadsAtEntity(e,123,104,238,0.8); });
})

//Holy Ice
register("playerInteract",() => {
    if(location.island != "The Rift") return;
    if(Player.getHeldItem()?.getName()?.removeFormatting()?.includes("Holy Ice")){
        HolyIce.reg(); setTimeout(() => { HolyIce.unreg(); }, 500);
    }
})

let HolyIce = {
    time : 0,
    activated : false,
    text : "",
    updateText() {
        if(this.activated) {
            if(1500 - (ServerTick.getTime() - this.time) <= 0) {
                this.activated = false;
                this.time = ServerTick.getTime();    
            } else
            HolyIce.text = "§bHoly Ice: §a" + timedisplay(1500 - (ServerTick.getTime() - this.time));
        } else {
            if(2500 - (ServerTick.getTime() - this.time) <= 0) {
                this.time = 0;
                HolyIce.text = "";
            } else
            HolyIce.text = "§bHoly Ice: §e" + timedisplay(2500 - (ServerTick.getTime() - this.time));
        }
    },
    reg() {this.trigger.register()},
    unreg() {this.trigger.unregister()},
    trigger : register("soundPlay",(position,name,vol,pitch,category,event) => {
        if(name == "random.drink") {
            HolyIce.activated = true;
            HolyIce.time = ServerTick.getTime();
            HolyIce.unreg();
        }
    }).unregister(),
}

register("renderOverlay" , () => {
    if(guiMover.gui.isOpen()) return;
    if(!settings.pigmansword || location.island != "The Rift") return;
    HolyIce.updateText();
    if(!HolyIce.time) return;
    DrawString(HolyIce.text , guiMover.settings.PigmanSword.x , guiMover.settings.PigmanSword.y , guiMover.settings.PigmanSword.s , true);
})


//EndStoneSword
const EndStoneSword = new Item(newItemStackFrom("minecraft:golden_sword",0,"{HideFlags: 254,ExtraAttributes: {id: \"END_STONE_SWORD\"}}"));
let EndStoneSwordStatus = {
    timer : 0,
    resistance : 0,
    damage : 0,
}
register("chat", (Resistance,damage,event) => {
    if(settings.EndStoneSword == 0 || !location.inSkyblock) return;
    EndStoneSwordStatus.resistance = Resistance;
    EndStoneSwordStatus.damage = damage;
    EndStoneSwordStatus.timer = ServerTick.getTime() + 5 * 1000;
}).setCriteria(/You now have ([0-9]+)% Damage Resistance for 5 seconds and \+([0-9]+)% damage on your next hit within 5 seconds!/)

register("playerInteract", (action,pos,event) => {
    if(settings.EndStoneSword < 2 || !location.inSkyblock) return;
    let item = Player.getHeldItem();
    if(item && getItemSBID(item) == "END_STONE_SWORD" && EndStoneSwordStatus.timer > ServerTick.getTime()) cancel(event);
})

register("renderOverlay" , () => {
    if(settings.EndStoneSword == 0) return;
    if(guiMover.gui.isOpen()) {
        EndStoneSword.draw(guiMover.settings.EndStoneSword.x , guiMover.settings.EndStoneSword.y + 1 , guiMover.settings.EndStoneSword.s);
        DrawString("     §a❈ 50%",guiMover.settings.EndStoneSword.x , guiMover.settings.EndStoneSword.y , guiMover.settings.EndStoneSword.s, true);
        DrawString("     §e3.141s",guiMover.settings.EndStoneSword.x , guiMover.settings.EndStoneSword.y + 9 * guiMover.settings.EndStoneSword.s , guiMover.settings.EndStoneSword.s, true);
        return;
    }
    if(settings.EndStoneSword == 2 || !location.inSkyblock) return;
    if(EndStoneSwordStatus.timer < ServerTick.getTime()) return;
    EndStoneSword.draw(guiMover.settings.EndStoneSword.x , guiMover.settings.EndStoneSword.y + 1 , guiMover.settings.EndStoneSword.s);
    DrawString(`     §a❈ ${EndStoneSwordStatus.resistance}%`,guiMover.settings.EndStoneSword.x , guiMover.settings.EndStoneSword.y , guiMover.settings.EndStoneSword.s, true);
    DrawString(`     §e${timedisplay(EndStoneSwordStatus.timer - ServerTick.getTime())}`,guiMover.settings.EndStoneSword.x , guiMover.settings.EndStoneSword.y + 9 * guiMover.settings.EndStoneSword.s , guiMover.settings.EndStoneSword.s, true);
})

register("worldLoad", () => {
    EndStoneSwordStatus.damage = 0;
    EndStoneSwordStatus.resistance = 0;
    EndStoneSwordStatus.timer = 0;
})

//Re-heated Gummy Polar Bear   REHEATED_GUMMY_POLAR_BEAR   Smoldering Polarization I
let ReheatedGummyPolarBear = {};
try {
    Object.assign(ReheatedGummyPolarBear,JSON.parse(FileLib.read("./config/ChatTriggers/modules/BabyzombieAddons/config/ReheatedGummyPolarBear.json")));
} catch (error) {}

register("chat", (msg) => {
    if(!settings.ReheatedGummyPolarBear || !location.inSkyblock) return;
    ReheatedGummyPolarBear[location.SBProfile] = 60 * 60;
}).setCriteria("You ate a Re-heated Gummy Polar Bear${msg}")

function numberToTimeString(number) {
    let m = Math.floor(number / 60);
    let s = Math.floor(number%60);
    return (m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s;
}

register("step", () => {
    if(!location.inSkyblock || location.inDungeon || location.island == "The Rift" || !ReheatedGummyPolarBear[location.SBProfile] || ReheatedGummyPolarBear[location.SBProfile] <= 0) return;
    ReheatedGummyPolarBear[location.SBProfile]--;
    if(settings.ReheatedGummyPolarBear == 1 && location.location == "Smoldering Tomb" || settings.ReheatedGummyPolarBear == 2)
        switch (ReheatedGummyPolarBear[location.SBProfile]) {
            case 300:
                Client.showTitle("","§b小熊软糖持续时间还剩§c五分钟",0,90,10);
                World.playSound("random.orb",1,1);
                break;
            case 120:
                Client.showTitle("","§b小熊软糖持续时间还剩最后§c两分钟",0,90,10);
                World.playSound("random.orb",1,1);
                setTimeout(() => { World.playSound("random.orb",1,1); }, 200);
                break;
            case 60:
                Client.showTitle("","§b小熊软糖持续时间还剩最后§c60秒",0,90,10);
                World.playSound("random.orb",1,1);
                setTimeout(() => { World.playSound("random.orb",1,1); }, 200);
                setTimeout(() => { World.playSound("random.orb",1,1); }, 400);
                break;
            case 0:
                Client.showTitle("","§c小熊软糖效果结束",0,90,10);
                sendEssentialNotifications("§c小熊软糖效果结束,注意烈焰人!","",10);
                World.playSound("random.anvil_break",1,1);
                break;
        }
    if(ReheatedGummyPolarBear[location.SBProfile] == 0) delete ReheatedGummyPolarBear[location.SBProfile];
    FileLib.write("./config/ChatTriggers/modules/BabyzombieAddons/config/ReheatedGummyPolarBear.json",JSON.stringify(ReheatedGummyPolarBear,null,4),true);
    if(Object.keys(ReheatedGummyPolarBear).length === 0) FileLib.delete("./config/ChatTriggers/modules/BabyzombieAddons/config/ReheatedGummyPolarBear.json");
}).setDelay(1)

const PolarBearGummy = new Item(newItemStackFrom("minecraft:skull",3,"{HideFlags:254,SkullOwner:{Id:\"74ddb947-f95e-3d16-bfb8-8d7fdadba323\",Properties:{textures:[0:{Value:\"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNDMwNjU4N2VjMzhjMjQ0NmQzODlhNTgxZTA2OTE1NTZmYTU4ZmNlMGEwMmQwODQ2ZDIzZmQ2OGUzNjU2YTI0OSJ9fX0\u003d\"}]}},ExtraAttributes:{id:\"REHEATED_GUMMY_POLAR_BEAR\"}}"));
register("renderOverlay", () => {
    if(!settings.ReheatedGummyPolarBear) return;
    if(guiMover.gui.isOpen()) {
        PolarBearGummy.draw(guiMover.settings.ReheatedGummyPolarBear.x, guiMover.settings.ReheatedGummyPolarBear.y, guiMover.settings.ReheatedGummyPolarBear.s);
        DrawString("    §a" + numberToTimeString(ReheatedGummyPolarBear[location.SBProfile] ? ReheatedGummyPolarBear[location.SBProfile] : 1234),guiMover.settings.ReheatedGummyPolarBear.x, guiMover.settings.ReheatedGummyPolarBear.y + 2 * guiMover.settings.ReheatedGummyPolarBear.s, guiMover.settings.ReheatedGummyPolarBear.s,true);
        return;
    }
    if(!ReheatedGummyPolarBear[location.SBProfile] || ReheatedGummyPolarBear[location.SBProfile] <= 0) return;
    if(settings.ReheatedGummyPolarBear == 1 && location.location != "Smoldering Tomb") return;
    if(!location.inSkyblock || location.inDungeon || location.island == "The Rift") return;
    PolarBearGummy.draw(guiMover.settings.ReheatedGummyPolarBear.x, guiMover.settings.ReheatedGummyPolarBear.y, guiMover.settings.ReheatedGummyPolarBear.s);
    DrawString("    §a" + numberToTimeString(ReheatedGummyPolarBear[location.SBProfile]),guiMover.settings.ReheatedGummyPolarBear.x, guiMover.settings.ReheatedGummyPolarBear.y + 2 * guiMover.settings.ReheatedGummyPolarBear.s, guiMover.settings.ReheatedGummyPolarBear.s,true);
})